package cn.ipanel.bigdata.dw.realtime

import cn.ipanel.bigdata.boot.source.genre.Phoenix
import cn.ipanel.bigdata.dw.dws.HBASE_NAMESPACE
import cn.ipanel.bigdata.dw.{BaseColumns, SUM_REGION_SERVERS}
import org.apache.spark.sql.{Dataset, Row}

/**
 * @author lzz
 * @environment IntelliJ IDEA 2020.3.1
 * @projectName bigdata_shanxi
 * @date 2023/08/29 16:20
 * @description: 按小时统计在线离线设备数
 */
protected[realtime] object OnlineDeviceCT extends Phoenix(HBASE_NAMESPACE, "t_device_by_status") with BaseColumns {

  final val F_ONLINE_NUM           :String  = "f_online_num"                // 在线设备数
  final val F_OFFLINE_NUM          :String  = "f_offline_num"               // 离线设备数

  override def getTBColumns: Seq[String] = Seq(F_PERIOD_TIME, F_REGION, F_ONLINE_NUM, F_OFFLINE_NUM)

  override def buildTable: String = {
    s"""
       |CREATE TABLE IF NOT EXISTS $getDBName.$getTBName (
       |$F_PERIOD_TIME INTEGER NOT NULL
       |, $F_REGION BIGINT NOT NULL
       |, $F_ONLINE_NUM VARCHAR
       |, $F_OFFLINE_NUM BIGINT
       |constraint pk primary key
       |($F_PERIOD_TIME, $F_REGION)) salt_buckets = $SUM_REGION_SERVERS
       |""".stripMargin
  }

  override def emptyTable: Dataset[_] = {
    import spark.implicits._
    spark.createDataset(spark.sparkContext.emptyRDD[OnlineDeviceTable])
  }

  case class OnlineDeviceTable(f_period_time: Int,
                               f_region: Long,
                               f_online_num: Int,
                               f_offline_num: Int)

  object OnlineDeviceTable {

    def apply(row: Row): OnlineDeviceTable = {
      OnlineDeviceTable(row.getAs[Int](F_PERIOD_TIME)
        , row.getAs[Long](F_REGION)
        , row.getAs[Int](F_ONLINE_NUM)
        , row.getAs[Int](F_OFFLINE_NUM)
      )
    }
  }

}
